package br.com.skolar.client.framework;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;

public class Callback<T> implements AsyncCallback<T> {
	private boolean showSuccessMessage;
	protected final EventBus eventBus;
	private ParamCommand<T> sourceCommand, successCommand;

	@Inject
	public Callback(EventBus eventBus) {
		this.eventBus = eventBus;
	}

	@Override
	public void onFailure(Throwable caught) {
		eventBus.fireEvent(new FailureEvent(caught));
		if (sourceCommand!=null)
			sourceCommand.execute(null);
	}

	@Override
	public final void onSuccess(T result) {
		if (showSuccessMessage)
			eventBus.fireEvent(new SuccessEvent());
		if (sourceCommand!=null)
			sourceCommand.execute(result);
		if (successCommand!=null)
			successCommand.execute(result);
	}
	
	public Callback<T> showSuccessMessage() {
		showSuccessMessage = true;
		return this;
	}

	public Callback<T> onSuccess(Event sourceEvent) {
		sourceCommand = sourceEvent.callbackCommand;
		return this;
	}

	public Callback<T> onSuccess(Event sourceEvent, ParamCommand<T> command) {
		sourceCommand = sourceEvent.callbackCommand;
		successCommand = command;
		return this;
	}
}